package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

	@Autowired
	private UserAccountMapper userAccountMapper;

	@Autowired
	private UserAccountDetailMapper userAccountDetailMapper;

	@Override
	public void register(Long userId) {
		UserAccount userAccount = new UserAccount();
		userAccount.setUserId(userId);
		userAccount.setTotalAmount(new BigDecimal("1000.00"));
		userAccount.setAvailableAmount(new BigDecimal("1000.00"));
		userAccountMapper.insert(userAccount);
	}

	/**
	 * @author WeakMoon
	 * @date 2025/03/09 14:16:25
	 * 获取当前用户可用金额
	 */
	@Override
	public BigDecimal getAvailableAmount(Long userId) {
		//获取结果数据
		return userAccountMapper.selectOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId,userId)).getAvailableAmount();
	}

	/**
	 * @author WeakMoon
	 * @date 2025/03/10 15:47:40
	 * 检查及扣减账户余额
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean checkAndDeduct(AccountDeductVo accountDeductVo) {
		//执行Update语句
		int result = userAccountMapper.checkAndDeduct(accountDeductVo.getAmount(),accountDeductVo.getUserId());

		//判断修改数据集行数
		if (result > 0){
			//记录当前用户的资金明细
			this.addUserAccountDetail(accountDeductVo.getUserId(),accountDeductVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_MINUS,accountDeductVo.getAmount(),accountDeductVo.getOrderNo());
			return true;
		}
		return false;
	}

	/**
	 * @author WeakMoon
	 * @date 2025/03/10 16:09:35
	 * 记录当前账户资金明细
	 */
	public void addUserAccountDetail(Long userId, String content, String typeMinus, BigDecimal amount, String orderNo) {
		UserAccountDetail userAccountDetail = new UserAccountDetail();
		userAccountDetail.setUserId(userId);
		userAccountDetail.setTitle(content);
		userAccountDetail.setTradeType(typeMinus);
		userAccountDetail.setAmount(amount);
		userAccountDetail.setOrderNo(orderNo);
		userAccountDetailMapper.insert(userAccountDetail);
	}
}
